#include "bezier4.h"

Bezier4::Bezier4(int segs= 60)
{
       recalculate(segs);
}

Bezier4::~Bezier4()
{
        if(coefs)
                delete coefs;
}

void Bezier4::recalculate(int segs)
{
        if (coefs)
                delete coefs;

        coefs = new float[segments*4];

        float interv = 1.0/segments;
        float mu = 0.0f;

        for (int i = 0; i < segments; i++){
                float mum1 = 1.0f-mu;
                float mum13 = mum1*mum1*mum1;
                float mu3 = mum1*mum1;

                coefs[i] = mum13;
                coefs[i+segments] = 3*mu*mum1*mum1;
                coefs[i+segments*2] = 3*mu*mu*mum1;
                coefs[i+segments*3] = mu3;

                mu += interv;
        }
}
p3d Bezier4::getFromSeg(p3d p1,p3d p2,p3d p3, p3d p4, int seg)
{
    p3d tmp;    
    float m1 = coefs[seg];
    float m2 = coefs[seg+segments];
    float m3 = coefs[seg+segments*2];
    float m4 = coefs[seg+segments*3];

    tmp.x = p1.x * m1 + p2.x * m2 +  p3.x * m3+  p4.x * m4;
    tmp.y = p1.y * m1 + p2.y * m2 +  p3.y * m3+  p4.y * m4;
    tmp.z = p1.z * m1 + p2.z * m2 +  p3.z * m3+  p4.z * m4;

    return tmp;
};

p3d Bezier4::getFromMu(p3d p1, p3d p2,p3d p3, p3d p4,float mu)
{
    p3d tmp;

    int seg = (int) mu/segments;
    getFromSeg(p1,p2,p3,p4,seg);    

    return tmp;
};
